package com.gnerv.rabbitmq.agent.config;

import com.gnerv.rabbitmq.agent.cache.AgentCache;
import com.gnerv.rabbitmq.agent.tools.UUIDTools;
import com.google.common.io.Files;
import jakarta.annotation.PostConstruct;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;

import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;

/**
 * @author Gnerv LiGen
 */
@Slf4j
@Configuration
public class RabbitmqAgentConfig {

    private static final String UK_ID_PATH = "config/ukId";

    @PostConstruct
    private static void initUkId() {
        String currentDirectory = System.getProperty("user.dir");
        File ukIdFile = new File(currentDirectory, UK_ID_PATH);
        if (ukIdFile.exists()) {
            try {
                AgentCache.UK_ID = Files.asCharSource(ukIdFile, StandardCharsets.UTF_8).read();
            } catch (IOException e) {
                AgentCache.UK_ID = UUIDTools.lower();
                log.info("自动生成 agent 唯一 ukId");
            }
        } else {
            try {
                Files.createParentDirs(ukIdFile);
                Files.touch(ukIdFile);
                AgentCache.UK_ID = UUIDTools.lower();
                Files.write(AgentCache.UK_ID.getBytes(StandardCharsets.UTF_8), ukIdFile);
            } catch (IOException e) {
                log.info("创建 agent ukId 配置文件失败");
            }
        }
    }

}
